package algorithm.sort.mergeSort;

import java.util.Arrays;

public class Merge {

    public static void main(String[] args) {
        int[] arr ={19,97,9,17,1,8,27};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }


    public static void sort(int[] arr){
        int []temp = new int[arr.length];
        mergeSort(arr,0,arr.length-1,temp);
    }
    public static void mergeSort(int[] arr,int left,int right,int[] temp){
        //只要left小于right就继续分
        if (left < right){
            int mid = (left+right)/2;
            mergeSort(arr,left,mid,temp);
            mergeSort(arr,mid+1,right,temp);
            merge(arr,left,mid,right,temp);
        }
    }

    //合
    public static void merge(int[] arr,int left,int mid,int right,int[] temp){
        int i = left;
        int j = mid+1;
        int t = 0;
        while (i<=mid && j<=right){
            if (arr[i]>=arr[j]){
                temp[t++] = arr[j++];
            }else {
                temp[t++] = arr[i++];
            }
        }
        while(i<=mid){
            temp[t++] = arr[i++];
        }
        while(j<=right){
            temp[t++] = arr[j++];
        }

        //将临时数组中的值传到arr中
        t=0;
        while (left<=right){
            arr[left++] = temp[t++];
        }
    }
}
